﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using AutoGear.BLL;
using ECommerce.Library.DataStructure;
using ECommerce.Library.Web;
using ECommerce.Library;
using ECommerce.Library.ECommerce;
using Entity;
using System.Text;
using eShop.Model;
using eShop.Business;



public partial class controls_wucProduct : System.Web.UI.UserControl
{

    ShoppingCart _shoppingCart;
    ReadWriteCustomCollection<Favorites> _favorites;

    private int _productId;
    public int ProductId
    {
        get { return this._productId; }
        set { this._productId = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        
        LoadProductData();
        LoadProductAdditionalData();
        if (!Page.IsPostBack)
        {
            LoadSession();
            //BindData();
            GenerateSEOData();
           
        }
    }
    private void GenerateSEOData()
    {
        Product product = Product.Load(this._productId);
        if (product != null)
        {
            //Pierogi and Dumplings
            if (product.Category.CategoryId == 33 || product.Category.ParentCategoryId == 33)
            {

                SEOHelper.RenderTitle(this.Page, product.Category.CategoryName + " by Polana, a Polish experience of Gourmet Polish Food Online", true);
                SEOHelper.RenderMetaTag(this.Page, "description", "Authentic, traditional Polish Pierogi and Dumplings from Polana.", true);
                SEOHelper.RenderMetaTag(this.Page, "keywords", "authentic, buy polish food online, traditional, kielbasa, buy polish food, European sausage, fresh polish sausage, smoked sausage, smoked polish sausage, polish food, polish recipes, polish hams, polish bacons, fresh sausage, sausages, deli sausage, smoked sausages, blood sausages, polish blood sausage, polish wieners, headcheese, polish cheese, polish hams, polish blood sausage, polish bacon, wienners", true);
            }
                //sausages
            else if (product.Category.CategoryId == 37 || product.Category.ParentCategoryId == 37 )
            {
                Category cat = CategoryManager.GetById(product.Category.ParentCategoryId);

                SEOHelper.RenderTitle(this.Page, cat.CategoryName + " and " + product.Category.CategoryName + " and " + product.ProductName + " by Polana, a Polish experience of Gourmet Polish Food Online", true);
                SEOHelper.RenderMetaTag(this.Page, "description", "Authentic, traditional Polish sausages, kielbasa, smoked sausages, bacon, blood sausage and more from Polana.", true);
                SEOHelper.RenderMetaTag(this.Page, "keywords", "authentic, buy polish food online, traditional, kielbasa, buy polish food, European sausage, fresh polish sausage, smoked sausage, smoked polish sausage, polish food, polish recipes, polish hams, polish bacons, fresh sausage, sausages, deli sausage, smoked sausages, blood sausages, polish blood sausage, polish wieners, headcheese, polish cheese, polish hams, polish blood sausage, polish bacon, wienners", true);
            }
                //Steak
            else if (product.Category.CategoryId == 72 || product.Category.ParentCategoryId == 72)
            {
                Category cat = CategoryManager.GetById(product.Category.CategoryId);
                SEOHelper.RenderTitle(this.Page, cat.CategoryName + " and " + product.Category.CategoryName + " and " + product.ProductName + " by Polana, a Polish experience of Gourmet Polish Food Online", true);
                SEOHelper.RenderMetaTag(this.Page, "description", "Authentic, traditional Polish rib eyes, Kansas City steaks, cube steaks, lean chucks, sirloins, top sirloins and more from Polana.", true);
                SEOHelper.RenderMetaTag(this.Page, "keywords", "buy polish food, buy polish food online, polish, online, European sausage, fresh polish sausage, polish food online, order polish food, polish recipes, round steak, sirloin steak, rib eye steak, rib eye lean, USDA prime rib, round rib eye, round rib, round ground sirloin, dry aged sirloin, top sirloin", true);
            }
                //Prepared Polish Dishes
            else if (product.Category.CategoryId == 46 || product.Category.ParentCategoryId == 46)
            {
                Category cat = CategoryManager.GetById(product.Category.CategoryId);

                SEOHelper.RenderTitle(this.Page, cat.CategoryName + " and " + product.Category.CategoryName + " and " + product.ProductName + " by Polana, a Polish experience of Gourmet Polish Food Online", true);
                SEOHelper.RenderMetaTag(this.Page, "description", "Buy Polish dishes, Polish pastries, European steaks and sausages, fresh polish sausage, smoked sausages, and more from Polana.", true);
                SEOHelper.RenderMetaTag(this.Page, "keywords", "buy polish food, polish, buy polish food online, online, European sausage, fresh polish sausage, polish food online, order polish food, polish recipes, polish dishes, prepared polish dishes, premade polish, stuffed cabbage, polish cabbage, polish potato pancakes, golabki, blintzes, potato pancakes, croquettes, polish soup, polish stew, soups and stews, polish blintzes, cheese blintzes, cherry blintzes, apple blintzes, strawberry blintzes, kraut, krupnik, kapusniak, barszcz, polish dumplings, polish soup, bigos, flaki", true);
            }
            //Bakery
            else if (product.Category.CategoryId == 52 || product.Category.ParentCategoryId == 52)
            {
                Category cat = CategoryManager.GetById(product.Category.CategoryId);
                SEOHelper.RenderTitle(this.Page, cat.CategoryName + " and " + product.Category.CategoryName + " and " + product.ProductName + "by Polana, a Polish experience of Gourmet Polish Food Online", true);
                SEOHelper.RenderMetaTag(this.Page, "description", "Fresh, top-quality bread, cakes, pastries, torts, and other baked goods from Polana.", true);
                SEOHelper.RenderMetaTag(this.Page, "keywords", "buy polish food, polish baked goods, polish, bread, cakes, cheesecakes, pastry, pastries, torts, polish bread, polish cake, polish cheesecake, polish pastries, polish torts, rye bread, dark oat bread, polish rye bread, polish dark oat bread, seven grain bread, village loaf, fitnessbread, chalka, polish layered honey cake, polish marzipan, polish tort, polish torts, fitness bread, yeast sweet bread, layered honey spice cake, marzipan roulade, yeast poppy seed breadk, poppy seed roll, makowiec, babka, rum and raisin babka, pound babka, piaskowa, polish coffee cake, cheese coffee cake, kolacz, cinnamon walnut coffee cake, baumkuchen, sekacz, kolaczki, paczki, rugelch, poznaski, chocolate raspberry tort,  cappuccino tort, straciatella", true);
            }
            //Pantry
            else if (product.Category.CategoryId ==58  || product.Category.ParentCategoryId == 58 )
            {
                Category cat = CategoryManager.GetById(product.Category.CategoryId);
                SEOHelper.RenderTitle(this.Page, cat.CategoryName + " and " + product.Category.CategoryName + " and " + product.ProductName + " by Polana, a Polish experience of Gourmet Polish Food Online", true);
                SEOHelper.RenderMetaTag(this.Page, "description", "Traditional, quality teas, coffees, canned goods, dry goods, jams, preserves, soup, cookies, chocolates, candies and more from Polana.", true);
                SEOHelper.RenderMetaTag(this.Page, "keywords", "buy polish food, polish, online, polish cookies, polish chocolates, polish candies, polish biscuits, pierniczki, torcik wedlowski, sezamki, ptasie mleczko, marzipan, polish soup, Wedel chocolate, borowik, cabbage soup, vegetable soup, red beets barszcz, portabella mushroom soup, king boletus soup, oplatek, dry red capped mushroom, dry bay boletus, podkrzy brunatny, jarzynka, warzwko, white barszcz, zurek, Ukrainian barszcz, gherkins, cwikia, polish jams, polish preserves,  beetroot salad, polish dill pickles, sorrel, sauerkraut, redcurrant jam, blackcurrant jam, blackberry jam, gooseberry jam, plum jam, powidlo, cherry jam, Kosciuszko mustard, zurek zakwas, sarepska, horseradish mustard, inka, nettle leaf tea, pokrzywa, truskawka, czwrna porzeczka, grejfrut, owce lasu, aronia, zurawina, jablko, forest tea, grapefruit tea, blackcurrant tea, aronie tea, malina, rumiankek, dzika roza, Melissa tea, fennel tea, koper wloski, dziurawiec ", true);
            }
            SEOHelper.RenderMetaTag(this.Page, "robots", "ALL", true);
        }
    }
    private void LoadProductAdditionalData()
    {
        IList<TblProductAdditionalImage> additionalImages = TblProductAdditionalImage.GetTblProductAdditionalImageByProductID(this._productId);

        rptAdditionalViews.DataSource = additionalImages;
        rptAdditionalViews.DataBind();

        rptGalleryLinks.DataSource = additionalImages;
        rptGalleryLinks.DataBind();

        //rptImageGallery.DataSource = additionalImages;
        //rptImageGallery.DataBind();

        //ReadWriteCustomCollection<Product> relatedProducts = Product.FeaturedProducts(1000);
        Product product = Product.Load(this._productId);
        ReadWriteCustomCollection<Product> relatedProducts = Product.RelatedProducts(1000,product.Category.CategoryId,product.ProductId);
        if (relatedProducts != null && relatedProducts.Count > 0)
        {
            rprProductLikes.DataSource = relatedProducts;
            rprProductLikes.DataBind();
            dvRelatedProducts.Visible = true;
        }
        else
        {
            dvRelatedProducts.Visible = false;
        }
    }
    protected void rprProductLikes_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Product product = (Product)e.Item.DataItem;
            if (product != null)
            {
                HtmlImage imgAdditionalImage = (HtmlImage)e.Item.FindControl("imgAdditionalImage");
                Label lblProductName = (Label)e.Item.FindControl("lblProductName");
                HtmlAnchor lnkProduct = (HtmlAnchor)e.Item.FindControl("lnkProduct");
                HtmlAnchor lnkProductNameLink = (HtmlAnchor)e.Item.FindControl("lnkProductNameLink");

                string productName = product.ProductName;
                lblProductName.ToolTip = productName;
                if (productName.Length > 20)
                    productName = String.Format("{0}...", productName.Substring(0, 12));
                lblProductName.Text = productName;

                string imageUrl = ImageResizer.CheckImageMissing(product.ProductImageSmallThumbnail, AutoGear.BLL.SiteSettings.NoImageDetailSizeUrl);
                if (imageUrl.Contains("~"))
                    imageUrl = ResolveUrl(imageUrl);
                imgAdditionalImage.Src = imageUrl;

                lnkProduct.HRef = Page.ResolveUrl(product.ProductUrl);
                lnkProductNameLink.HRef = Page.ResolveUrl(product.ProductUrl);
            }
        }

    }
    private void LoadProductData()
    {
        Product product = Product.Load(this._productId);

        Page.ClientScript.RegisterStartupScript(typeof(Page), "_MENU_TOGGLE", String.Format("ToggleChildVisibility({0});", product.Category.ParentCategoryId), true);
        Page.ClientScript.RegisterStartupScript(typeof(Page), "_SELECTCATMENU", String.Format("SetCurrentCategory({0});", product.Category.CategoryId), true);

        this.AddProductToRecentlyViewedProducts(product);        

        //lblPrice.Text = "$" + product.ProductPrice.ToString();// Utility.FormatPriceText(product.ProductPrice);
        lblPrice.Text = Utility.FormatPriceText(product.ProductPrice);
        if (product.StandardCost > 0)
        {
            lblSalePrice.Text = Utility.FormatPriceText(product.StandardCost);
            lblPrice.CssClass = "product-detail-price-x";
        }
        else 
        {
            lblPrice.CssClass = "product-detail-price";
        }
        if (product.AdditionalPrice > 0)
        {
            lblAdditionalPrice.Visible = true;
            lblAdditionalPrice.Text ="+"+" "+ECommerce.Library.ECommerce.Utility.FormatPriceText(product.AdditionalPrice) +" " + product.AdditionalPriceDesc;
        }
        else
        {
            lblAdditionalPrice.Visible = false;
        }
        //lblItemNumber.Text = product.ItemNumber;
        //lblBrandName.Text = product.Brand.BrandName;
        lblProductName.Text = product.ProductName;
        lblProductName2.Text = product.ProductName2;
        lblDescription.Text = Server.HtmlDecode(product.ProductDescription);
        if (Server.HtmlDecode(product.ProductDescription).Length < 1) 
        {
            tabDescription.Style.Add("Display","none");
        }
        if (Server.HtmlDecode(product.Recipies).Length < 1) 
        {
            tabRecipes.Style.Add("Display", "none");
        }
      
        if (Server.HtmlDecode(product.AdditionalInfo).Length < 1)
        {
            tabAdditional.Style.Add("Display", "none");
        }

        //lblMetalType.Text = product.IsClearenceItem ? "White Gold" : "Yellow Gold";
        
        lblItemNo.Text = product.ItemNumber;
        ProductStock stock = product.Stocks[0];
        lblWeight.Text = Convert.ToString(stock.Weight) + " lbs ";
        if (!string.IsNullOrEmpty(stock.WeightUnit))
        {
            if (Convert.ToDecimal(stock.WeightUnit) > 0)
            {
                lblWeightUnit.Text = Convert.ToString(stock.WeightUnit) + " oz.";
            }
            else 
            {
                lblWeightUnit.Text = "0" + "Oz.";
            }
        }
        lblSize.Text = stock.Size;
        rptSiteMap.DataSource = CategoryManager.GetSubCategorySiteMapTree(SiteUtility.SuperRootCategoryId, product.Category.CategoryId);
        rptSiteMap.DataBind();

        //hlkProductLink.NavigateUrl = product.ProductUrl;
        hlkProductLink.Text = product.ProductName;

        System.Drawing.Size originalImageDimension = ImageResizer.GetImageDimension(product.ProductImageDetailSize);
        if (originalImageDimension.Width > 250)
        {
            imgProductDetailImage.Style.Add("width", "250px;");
        }
        if (originalImageDimension.Height > 200)
        {
            imgProductDetailImage.Style.Add("height", "200px;");
        }
        imgProductDetailImage.Src = String.Format("{0}_services/getListingThumb.aspx?file={1}&w=274&h=323", SiteGlobals.BaseUrl, ImageResizer.CheckImageMissing(product.ProductImageDetailSize, AutoGear.BLL.SiteSettings.NoImageDetailSizeUrl));
        lnkEnlargeImage.HRef = String.Format("{0}?KeepThis=true&TB_iframe=true", ImageResizer.CheckImageMissing(product.ProductImageMaxSize, AutoGear.BLL.SiteSettings.NoImageMaxSizeUrl));
        lbRecipes.Text = Server.HtmlDecode(product.Recipies);
        lbAdditionalInfo.Text = Server.HtmlDecode(product.AdditionalInfo);
        LoadReviews();
    }

    private void LoadReviews()
    {
        ECommerce.DAL.CustomCollection<TblProductReview> review = TblProductReview.GetTblProductReviewByProductId(this._productId);
        StringBuilder reviewsHtml = new StringBuilder();
        if (review != null && review.Count > 0)
        {
            int countRating = 0;
            
            ReviewCount.Text = review.Count.ToString();
            for (int i = 0; i < review.Count; i++)
            {
                countRating = countRating + Convert.ToInt32(review[i].RatingValue);
                //reviewsHtml.AppendFormat("<strong>{0}</strong>({1})<br />{2}<hr />", review[i].CustomerName, review[i].CustomerEmail, review[i].ReviewText);
            }
            rptReviews.DataSource = review;
            rptReviews.DataBind();

            countRating = Convert.ToInt32(countRating / review.Count);
            litReviewAvg.Text = countRating.ToString();
            Rating.CurrentRating = countRating;
        }
        else
        {
            tabReview.Style.Add("Display", "none");
        }
    }

    protected void rptReviews_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            TblProductReview currentReview = (TblProductReview)e.Item.DataItem;
            if (currentReview != null)
            {
                AjaxControlToolkit.Rating ReviewRating = (AjaxControlToolkit.Rating)e.Item.FindControl("ReviewRating");
                ReviewRating.CurrentRating = Convert.ToInt32(currentReview.RatingValue);
            }
        }
    }

    private void AddProductToRecentlyViewedProducts(Product product)
    {
        List<Product> recentProducts = AutoGearSessionManager.RecentlyViewedProducts;

        if (recentProducts != null && recentProducts.Count > 0)
        {
            recentProducts.RemoveAll(delegate(Product p) { return p.ProductId.Equals(product.ProductId); });
        }

        recentProducts.Add(product);

        AutoGearSessionManager.RecentlyViewedProducts = recentProducts;
    }

    protected ReadWriteCustomCollection<KeyValuePair<string, string>> GetDefaultSiteMap()
    {
        ReadWriteCustomCollection<KeyValuePair<string, string>> node = new ReadWriteCustomCollection<KeyValuePair<string, string>>();
        node.Add(new KeyValuePair<string, string>("Home", AutoGear.BLL.CustomSiteMap.Home));
        node.Add(new KeyValuePair<string, string>("Products", AutoGear.BLL.CustomSiteMap.Products));
        return node;
    }


    protected void rptSiteMap_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        try
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                HyperLink hlkSiteMap = (HyperLink)e.Item.FindControl("hlkSiteMap");
                KeyValuePair<string, string> node = (KeyValuePair<string, string>)e.Item.DataItem;
                hlkSiteMap.NavigateUrl = node.Value;
                hlkSiteMap.Text = node.Key.ToLower() == "none" ? "Home" : node.Key;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    protected void imbAddToCart_Click(object sender, EventArgs e)
    {
        int qty;
        int.TryParse(tbxQuantity.Text.ToString().Trim(), out qty);
        string strMetalType = string.Empty;
        string strGiftWrapper = string.Empty;
        Product product = Product.Load(_productId);
        if (qty > 0)
        {
        
            this.AddCartItemToShoppingCart(qty, product, strMetalType, strGiftWrapper);
            lblMsgProductName.Text = product.ProductName;
            if (product.StandardCost > 0)
            {
                lblMsgPrice.Text = Utility.FormatPriceText(product.StandardCost + product.AdditionalPrice);
            }
            else 
            {
                lblMsgPrice.Text = Utility.FormatPriceText(product.ProductPrice + product.AdditionalPrice);
            }
            lblMsgQuantity.Text = tbxQuantity.Text;
            lblMsgTotal.Text = AutoGearSessionManager.ShoppingCart.TotalCartItem + AutoGearSessionManager.ShoppingCart.TotalGiftItem + " Items";
            LoadSession();
            
            UpdatePanel upnlShoppingBasket=(UpdatePanel)this.Page.Master.FindControl("upnlShoppingBasket");
            Literal litShoppingCartTotal = (Literal)upnlShoppingBasket.FindControl("litShoppingCartTotal");
            double grandTotal=AutoGearSessionManager.ShoppingCart.SubTotal + AutoGearSessionManager.ShoppingCart.GiftSubTotal;
            litShoppingCartTotal.Text = string.Format("{0:c}", grandTotal);
            upnlShoppingBasket.Update();

            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "_showblockui", "ShowConfirm(true);", true);
            imbCheckout.Visible = true;
            //uccResponseMessage.Visible = true;
            //uccResponseMessage.SetSuccessMessage("Product added successfully.");
        }
        else
        {
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "_showblockui", "ShowConfirm(false);", true);
            //uccResponseMessage.Visible = true;
            //uccResponseMessage.SetFailMessage("Invalid Quantity.");
        }
    }
    protected void AddCartItemToShoppingCart(int qty, Product product, string MetalType, string GiftWrapper)
    {
        ShoppingCart shoppingcart = AutoGearSessionManager.ShoppingCart;
        CartItem cartItem = new CartItem(product, qty, MetalType, GiftWrapper);
        shoppingcart.AddCartItem(cartItem);
        AutoGearSessionManager.ShoppingCart = shoppingcart;
    }
   
    protected void rptImageGallery_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
      
    }


    protected void rptShoppingCart_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            //CheckBox cbxSelectAll = (CheckBox)e.Item.FindControl("cbxSelectAll");
            //cbxSelectAll.Attributes.Add("onclick", "javascript:SelectAll('" + rptShoppingCart.ClientID + "','" + cbxSelectAll.ClientID + "','cbxSelect')");
        }
        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            CartItem cartItem = (CartItem)e.Item.DataItem;
            if (cartItem.Product.ProductId > 0)
            {

                HyperLink hlkItem = (HyperLink)e.Item.FindControl("hlkItem");
                hlkItem.NavigateUrl = cartItem.Product.ProductUrl;
                hlkItem.Text = cartItem.Product.ProductName;

                Image imgItemImage = (Image)e.Item.FindControl("imgItemImage");
                imgItemImage.ImageUrl = ImageResizer.CheckImageMissing(cartItem.Product.ProductImageSmallThumbnail, AutoGear.BLL.SiteSettings.NoImageSmallThumbnailUrl);

                Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");
                lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.Product.ProductPrice);

                Label lblItemNumber = (Label)e.Item.FindControl("lblItemNumber");
                lblItemNumber.Text = "Item Number: " + cartItem.Product.ItemNumber;

                Label lblMetalType = (Label)e.Item.FindControl("lblMetalType"); //+++ 062610
                lblMetalType.Text = "Class Type: " + cartItem.MetalType.ToString(); //+++ 062610


                Label lblGiftWrapper = (Label)e.Item.FindControl("lblGiftWrapper"); //+++ 062610
                lblGiftWrapper.Text = "Free gift wrap: " + cartItem.GiftWrapper.ToString(); //+++ 062610

                Label lblQuantity = (Label)e.Item.FindControl("lblQuantity");
                lblQuantity.Text = cartItem.Quantity.ToString();

            }

        }

    }

    protected void LoadSession()
    {
        _shoppingCart = AutoGearSessionManager.ShoppingCart;
        _favorites = AutoGearSessionManager.FavoritesList;
    }

    protected void imbCheckout_Click(object sender, EventArgs e)
    {
        if (SessionManager.IsUserLoggedIn)
        {
            AutoGearSessionManager.CheckoutSteps = CheckoutSteps.PreCheckout;
            Response.Redirect(CustomSiteMap.ShoppingCart);
        }
        else
        {
            AutoGearSessionManager.CheckoutSteps = CheckoutSteps.ShoppingCart;
            Response.Redirect(CustomSiteMap.ShoppingCart);
        }
    }
    protected void lnkAddToWishList_Click(object sender, EventArgs e)
    {
        try
        {
            if (SessionManager.IsUserLoggedIn)
            {
                TblProductWishList wishList = new TblProductWishList();
                wishList.ProductId = this._productId;
                wishList.SystemUserId = SessionManager.LoggedUser.UserId;
                wishList.Save();
                if (wishList.ProductWishListId != 0)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "ShowWishList('Successfully added to your wishlist');", true);
                }
                else 
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "ShowWishList('Already exists in your wishlist');", true);
                }

            }
            else 
            {
                Response.Redirect("~/login.aspx?ReturnUrl=" + Server.UrlEncode(Request.Path));
            }
            //BindInfo();
        }
        catch (Exception ex)
        {
            
        }
    }
    protected void btnSaveReview_Click(object sender, EventArgs e)
    {
        int lastReviewId = SaveReview();
        LoadReviews();

        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "_HIDEREVIEWMODAL", "$.modal.close(); $('#tabs').tabs('select', 2);", true);
        //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "_SCROLLTOREVIEW", String.Format("$(document).ready(function () {{ $('html,body').animate({{ scrollTop: $('#Review{0}').offset().top }}, {{ duration: 'slow', easing: 'swing' }}); }});", lastReviewId), true);
        ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "_PENDINGALERT", "jAlert('<b>Your review is pending administrator approval and will be published once it is approved.<b>', 'Notification');", true);

        Email.SendGenericEmail("Admin", SiteSettings.AdminEmail, "New Review Pending Moderation", String.Format("A new product review has been submitted. Please visit the following link <a href='"+SiteGlobals.BaseUrl+"admin/product-review-edit.aspx?rid={1}'>{0}admin/product-review-edit.aspx?rid={1}</a> to approve/disapprove.", SiteGlobals.BaseUrl, lastReviewId));
    }
    private int SaveReview()
    {
        TblProductReview newReview = new TblProductReview();
        newReview.ProductId = this._productId;
        newReview.CustomerName = txtReviewerName.Text;
        newReview.CustomerEmail = txtReviewerEmail.Text;
        newReview.ReviewText = Server.HtmlEncode(txtComment.Text.Replace("\n", "<br />"));
        newReview.RatingValue = Convert.ToInt32(Session["_lastRatingValue"].ToString());
        newReview.ReviewDate = DateTime.Now;
        newReview.IsApproved = false;
        //newReview.Save();
        return TblProductReview.CreateNewTblProductReview(newReview);
    }
    protected void Rating_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
    {
        Session["_lastRatingValue"] = e.Value;
    }
}
